package com.guchenbo.example.httpclient;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.httpclient.params.DefaultHttpParams;
import org.apache.commons.httpclient.params.HttpParams;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author penglai
 * @Date 2016/10/4.
 */
public class HttpUtils {

    public static String get(String url) {
        return get(url, null);
    }

    public static String get(String url, HeaderModel headerModel) {
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpRequestBase httpRequest = new HttpGet(url);

        CloseableHttpResponse httpResponse = null;
        try {

            if (headerModel != null) {
                setHeader(httpRequest, headerModel);
            }

            httpResponse = httpClient.execute(httpRequest);
            HttpEntity entity = httpResponse.getEntity();

            result = EntityUtils.toString(entity);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            HttpClientUtils.closeQuietly(httpResponse);
        }
        return result;
    }

    public static void setHeader(HttpRequestBase httpRequest, HeaderModel headerModel) {

        addCookies(httpRequest, headerModel);
    }

    public static void addCookies(HttpRequestBase httpRequest, HeaderModel headerModel) {
        List<CookieModel> cookies = headerModel.getCookies();
        if (CollectionUtils.isNotEmpty(cookies)) {
            List<String> cks = new ArrayList<>();

            for (CookieModel cookieModel : cookies) {
                cks.add(cookieModel.getValue());
            }

            String ck = StringUtils.join(cks, ",");
            httpRequest.setHeader("Cookie", ck);
        }
    }

    public static byte[] getEntity(String url) {
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpRequestBase httpRequest = new HttpGet(url);

        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(httpRequest);
            HttpEntity entity = httpResponse.getEntity();
            return IOUtils.toByteArray(entity.getContent());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            HttpClientUtils.closeQuietly(httpResponse);
        }
        return null;
    }

    public static long download(String url, String filePath, String fileName) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpRequestBase httpRequest = new HttpGet(url);

        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(httpRequest);
            HttpEntity entity = httpResponse.getEntity();

            InputStream inputStream = entity.getContent();
            File dir = new File(filePath);
            if (dir.exists()) {
                dir.delete();
            } else {
                dir.mkdirs();
            }

            File file = new File(dir, fileName);
            FileOutputStream outputStream = new FileOutputStream(file);
            IOUtils.copy(inputStream, outputStream);
            return file.length();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            HttpClientUtils.closeQuietly(httpResponse);
        }
        return 0;
    }

    public static String post(String url, Map<String, String> params) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httPost = new HttpPost(url);

        CloseableHttpResponse httpResponse = null;
        try {
            if (params != null) {
                List<NameValuePair> nvps = setParams(params);
                httPost.setEntity(new UrlEncodedFormEntity(nvps));
            }

            HttpParams httpParams = new DefaultHttpParams();
            httPost.setHeader("Referer", "http://www.ximalaya.com/passport/login");

            httpResponse = httpClient.execute(httPost);
            HttpEntity entity = httpResponse.getEntity();

            return EntityUtils.toString(entity);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            HttpClientUtils.closeQuietly(httpResponse);
        }
        return "";
    }

    public static List<NameValuePair> setParams(Map<String, String> params) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        return nvps;
    }

    public static String getHtmlGet(String url) {
        return get(url);
    }

    public static String toString(HttpEntity entity) {
        return toString(entity, null);
    }

    public static String toString(HttpEntity entity, Charset defaultCharset) {
        InputStream input = null;
        try {
            input = entity.getContent();
            Charset charset = null;
            try {
                ContentType contentType = ContentType.get(entity);
                if (contentType != null) {
                    charset = contentType.getCharset();
                }
                if (charset == null) {
                    charset = defaultCharset;
                }
                if (charset == null) {
                    charset = Charset.forName("UTF-8");
                }
            } catch (Exception e) {
                charset = Charset.forName("UTF-8");
            }
            return IOUtils.toString(input, charset);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(input);
        }
        return "";
    }

    public static String toString(InputStream input, Charset charset) {
        try {
            try {
                if (charset == null) {
                    charset = Charset.forName("UTF-8");
                }
            } catch (Exception e) {
                charset = Charset.forName("UTF-8");
            }
            return IOUtils.toString(input, charset);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(input);
        }
        return "";
    }


}
